package com.xdjd.mobile.business.api.my;

import com.gitee.easyopen.ApiConfig;
import com.gitee.easyopen.ApiContext;
import com.gitee.easyopen.annotation.Api;
import com.gitee.easyopen.annotation.ApiService;
import com.gitee.easyopen.doc.DataType;
import com.gitee.easyopen.doc.annotation.ApiDoc;
import com.gitee.easyopen.doc.annotation.ApiDocField;
import com.gitee.easyopen.doc.annotation.ApiDocMethod;
import com.gitee.easyopen.exception.ApiException;
import com.gitee.easyopen.session.SessionManager;
import com.xdjd.mobile.business.api.BaseApi;
import com.xdjd.mobile.business.constant.IsLoginStatus;
import com.xdjd.mobile.business.constant.UserSourceEnum;
import com.xdjd.mobile.business.entity.model.member.MemberUserPo;
import com.xdjd.mobile.business.entity.param.my.EditUserInfoParam;
import com.xdjd.mobile.business.entity.param.my.LoginParam;
import com.xdjd.mobile.business.entity.param.my.PictureParam;
import com.xdjd.mobile.business.entity.param.my.VerifyCodeParam;
import com.xdjd.mobile.business.entity.result.my.CheckLoginVo;
import com.xdjd.mobile.business.entity.result.my.LoginResult;
import com.xdjd.mobile.business.entity.result.my.UserWalletResult;
import com.xdjd.mobile.business.entity.vo.LoginUser;
import com.xdjd.mobile.business.service.MemberService;
import com.xdjd.mobile.business.service.VerifyCodeService;
import com.xdjd.mobile.business.util.ValidateCodeUtil;
import com.xdjd.mobile.system.ApiUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2019/1/8 0008.
 */
@ApiService
@ApiDoc("user")
public class UserApi extends BaseApi {

    @Autowired
    private MemberService memberService;
    @Autowired
    private VerifyCodeService verifyCodeService;

    @Api(name = "user.logout")
    @ApiDocMethod(description = "退出登录")
    public void logout() {
        ApiConfig apiConfig = ApiContext.getApiConfig();
        String token = ApiContext.getApiParam().fatchAccessToken();
        SessionManager sessionManager = apiConfig.getSessionManager();
        HttpSession session = sessionManager.getSession(token);
        session.setAttribute("xdjd-user", null);
    }

    /**
     * 获取图片验证码
     */
    @Api(name = "nologin.user.pic.send")
    @ApiDocMethod(description = "获取图片验证码",
            params = {@ApiDocField(name = "deviceNo", required = true,
                    description = "设备号", dataType = DataType.STRING, example = "ASDADSADFG")},
            results = {@ApiDocField(description = "图片验证码", dataType = DataType.STRING)})
    public String getPicCode(PictureParam param) {
        if (StringUtils.isEmpty(param.getDeviceNo()))
            return null;
        ValidateCodeUtil.Validate validate = ValidateCodeUtil.getRandomCode();
        String value = validate.getValue();
        redisTemplate.opsForValue().set(param.getDeviceNo(), value);
        redisTemplate.expire(param.getDeviceNo(), 120, TimeUnit.SECONDS);
        return validate.getBase64Str();
    }

    @Api(name = "nologin.user.sms.send")
    @ApiDocMethod(description = "发送短信")
    public void sendVerifyCode(VerifyCodeParam codeParam) {
//        Object picCode = redisTemplate.opsForValue().get(codeParam.getDeviceNo());
//        if (null == picCode)
//            throw new ApiException("图片验证码过期", "-1");
//
//        if (!codeParam.getPicCode().equalsIgnoreCase((String) picCode)) {
//            throw new ApiException("图片验证码错误, 请重新输入", "-1");
//        }
//        redisTemplate.delete(codeParam.getDeviceNo());
        verifyCodeService.sendVerifyCode(codeParam);
    }

    @Api(name = "nologin.user.login")
    @ApiDocMethod(description = "用户登录 （未登录需要登录code是：-101）")
    public LoginResult login(LoginParam param) {
        LoginResult result = new LoginResult();
        String appKey = ApiContext.getApiParam().fatchAppKey();
        param.setSource(UserSourceEnum.getByDesc(appKey).getCode().byteValue());
        param.setDevice(ApiContext.getApiParam().getString("deviceNo"));
        MemberUserPo userPo = memberService.login(param);
        BeanUtils.copyProperties(userPo, result);
        result.setMemberId(userPo.getId());
        return result;
    }

    @Api(name = "user.myself.info")
    @ApiDocMethod(description = "我的信息（包含钱包和步数信息）")
    public UserWalletResult findUserWalletInfo() {
        LoginUser currentUser = ApiUtil.getCurrentUser();
        return memberService.findUserWalletInfo(currentUser.getId());
    }

    @Api(name = "nologin.check.login")
    @ApiDocMethod(description = "校验是否登录")
    public CheckLoginVo checkLogin() {
        CheckLoginVo vo = new CheckLoginVo();
        LoginUser currentUser = ApiUtil.getCurrentUser();
        if (currentUser == null) {
            vo.setLoginType(IsLoginStatus.not_login.getCode().byteValue());
        } else {
            vo.setLoginType(IsLoginStatus.is_login.getCode().byteValue());
        }
        return vo;
    }


    @Api(name = "edit.user.info")
    @ApiDocMethod(description = "编辑用户信息")
    public void editUserInfo(EditUserInfoParam param) {
        LoginUser currentUser = ApiUtil.getCurrentUser();
        memberService.editUserInfo(param, currentUser.getId());
    }
}
